package org.brownhouse.rss;

import org.apache.log4j.Logger;
import org.brownhouse.rss.torrent.Torrent;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

/**

 */
public class RssTorrentReader implements TorrentReader {
    public static final Logger log = Logger.getLogger(RssTorrentReader.class);

    private URL feedUrl;
    private Set<String> titleRegularExpression;

    public RssTorrentReader(URL feedUrl, Set<String> titleRegularExpression) {
        this.feedUrl = feedUrl;
        this.titleRegularExpression = titleRegularExpression;
    }

    public Set<Torrent> getTorrents() {
        Set<Torrent> ret = new HashSet<Torrent>();
        try {
            SAXReader xmlReader = new SAXReader();
            Document feedDom = xmlReader.read(feedUrl);

            List<Node> torrentNodes = feedDom.selectNodes("//rss/channel/item");

            for (Node node : torrentNodes) {
                Node titleNode = node.selectSingleNode("title");
                Node linkNode = node.selectSingleNode("link");
                if (titleNode != null && linkNode != null) {
                    addMatchingTorrent(ret, titleNode, linkNode);
                }
            }
        } catch (DocumentException e) {
            log.error("Error reading feed '" + feedUrl + "'. ", e);
        }

        return ret;
    }

    private void addMatchingTorrent(Set<Torrent> ret, Node titleNode, Node linkNode) {
        for (String regularExpression : titleRegularExpression) {
            if (Pattern.matches(regularExpression, titleNode.getStringValue())) {
                try {
                    ret.add(new Torrent(new URL(linkNode.getStringValue()), titleNode.getStringValue()));
                    break;
                } catch (MalformedURLException e) {
                    log.warn("Malformed torrent URL '" + linkNode.getStringValue() + "'. Ignoring torrent...");
                }
            }
        }
    }
}
